//
//  CashViewController.m
//  location
//
//  Created by Dongxiang Xu on 2025/10/16.
//

#import "CashViewController.h"
#import "PolicyWebViewController.h"
#import "CashTableViewCell.h"
#import "CashView.h"


@interface CashViewController ()

@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UIView *cardsContainer;
@property (nonatomic,strong) NSMutableArray<CashTableViewCell *> *cardViews;
@property (nonatomic,strong) UIView *footerView;
@property (nonatomic,strong) NSArray *cashArray;
@property (nonatomic,strong) UIView *selView;
@property (nonatomic,strong) UIImageView *memberInfo;
@property (nonatomic,strong) UIView *rightView;
@property (nonatomic,strong) UIImageView *extraImg;
@property (nonatomic,strong) UIButton *current;

@end

@implementation CashViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = LightBGColor;
 
    [self getVersion];
    [self initView];
}

- (void)initView
{
    _cashArray = @[[NSMutableDictionary dictionaryWithDictionary:@{@"img":@"close_cash",@"sel_img":@"close_cash_sel",@"sel":@"0"}],
                   [NSMutableDictionary dictionaryWithDictionary:@{@"img":@"silver_cash",@"sel_img":@"silver_cash_sel",@"sel":@"0"}],
                   [NSMutableDictionary dictionaryWithDictionary:@{@"img":@"gold_cash",@"sel_img":@"gold_cash_sel",@"sel":@"0"}]];

    self.cardViews = [NSMutableArray array];
    BOOL hasMembership = [self.groupInfo[@"membership"] isKindOfClass:[NSDictionary class]];

    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, NAVHEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT-NAVHEIGHT-129)];
    self.scrollView.backgroundColor = [UIColor clearColor];
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    if (@available(iOS 11.0, *)) {
        self.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    [self.view addSubview:self.scrollView];

    CGFloat currentY = 0.f;

    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, currentY, SCREEN_WIDTH, 84)];
    
    if ([self.groupInfo[@"membership"] isKindOfClass:[NSDictionary class]]) {
        [header setFrame:CGRectMake(0, 0, SCREEN_WIDTH, 250)];
        UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-182)/2, 0, 182, 182)];
        
        [header addSubview:img];
        
        UIView *infoView = [[UIView alloc] initWithFrame:CGRectMake(16, img.maxY+16, SCREEN_WIDTH-32, 32)];
        [header addSubview:infoView];

        UIImageView *memberIcon = [[UIImageView alloc] initWithFrame:CGRectMake(0, (infoView.height-30), 30, 30)];
        [infoView addSubview:memberIcon];
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(memberIcon.maxX+1, 0, 106, 32)];
        label.font = MEDIUM_FONT(26);
        [infoView addSubview:label];
        
        [infoView setFrame:CGRectMake((SCREEN_WIDTH-label.maxX)/2, img.maxY+16, label.maxX, 32)];
        
        if ([self.groupInfo[@"membership"][@"planType"] integerValue]==3) {
            img.image = [UIImage imageNamed:@"cash_gold"];
            memberIcon.image = [UIImage imageNamed:@"icon_gold"];
            label.text = @"黄金会员";
            label.textColor = GoldColor;
        }else if ([self.groupInfo[@"membership"][@"planType"] integerValue]==2){
            img.image = [UIImage imageNamed:@"cash_silver"];
            memberIcon.image = [UIImage imageNamed:@"icon_silver"];
            label.text = @"白银会员";
            label.textColor = NormalMainColor;
        }else if ([self.groupInfo[@"membership"][@"planType"] integerValue]==1){
            img.image = [UIImage imageNamed:@"cash_close"];
            memberIcon.image = [UIImage imageNamed:@"icon_close"];
            label.text = @"亲密会员";
            label.textColor = CloseColor;
        }
        
        UILabel *time = [[UILabel alloc] initWithFrame:CGRectMake(16, infoView.maxY+4, SCREEN_WIDTH-32, 16)];
        time.textAlignment = NSTextAlignmentCenter;
        time.font = REAL_MEDIUM_FONT(14);
        time.textColor = GraryTooHeavyColor;
        NSString *expireDate = [[[[self.groupInfo[@"membership"][@"expireTime"] stringByReplacingCharactersInRange:NSMakeRange(4, 1) withString:@"年"] stringByReplacingCharactersInRange:NSMakeRange(7, 1) withString:@"月"] stringByReplacingCharactersInRange:NSMakeRange(10, 1) withString:@"日"] substringToIndex:11];
        time.text = [NSString stringWithFormat:@"到期时间 %@",expireDate];
        [header addSubview:time];
        
    }else{
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(16, 16, SCREEN_WIDTH-32, 32)];
        title.font = MEDIUM_FONT(26);
        title.text = @"会员计划";
        title.textColor = RealBlackColor;
        [header addSubview:title];
        
        UILabel *subTitle = [[UILabel alloc] initWithFrame:CGRectMake(16, title.maxY+4, SCREEN_WIDTH-32, 32)];
        subTitle.font = REAL_MEDIUM_FONT(14);
        subTitle.text = @"足迹更安全、守护更安心";
        subTitle.textColor = GraryHeavyLightColor;
        [header addSubview:subTitle];
    }
    [self.scrollView addSubview:header];
    currentY = header.maxY;

    if (!hasMembership) {
        [self setupCardsContainerBelowY:currentY];
        currentY = self.cardsContainer.maxY;
    }

    UIView *footer = [[UIView alloc] initWithFrame:CGRectMake(0, currentY, SCREEN_WIDTH, 0)];
    [self.scrollView addSubview:footer];
    self.footerView = footer;

    UILabel *memberTitle = [[UILabel alloc] initWithFrame:CGRectMake(18, 26, SCREEN_WIDTH-36, 28)];
    memberTitle.text = @"会员权益";
    memberTitle.font = MEDIUM_FONT(17);
    memberTitle.textColor = RealBlackColor;
    [footer addSubview:memberTitle];
                  
    _rightView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH*0.28, memberTitle.maxY+12, SCREEN_WIDTH-SCREEN_WIDTH*0.28+SCREEN_WIDTH*0.4677, SCREEN_WIDTH*0.925)];
    _rightView.backgroundColor = LightBGColor;
    [footer addSubview:_rightView];
    
    _selView = [[UIView alloc] initWithFrame:CGRectMake(0, -(SCREEN_WIDTH*0.985-_rightView.height)/2, SCREEN_WIDTH*0.214, SCREEN_WIDTH*0.985)];
    _selView.layer.masksToBounds = YES;
    [_selView.layer setCornerRadius:16];
    _selView.backgroundColor = [UIColor colorWithRed:255/255.0 green:138/255.0 blue:182/255.0 alpha:0.2/1];
    [_rightView addSubview:_selView];
    
    _memberInfo = [[UIImageView alloc] initWithFrame:CGRectMake(-SCREEN_WIDTH*0.28, 0, SCREEN_WIDTH, _rightView.height)];
    [_rightView addSubview:_memberInfo];

    _extraImg = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH, _rightView.y-(SCREEN_WIDTH*0.985-_rightView.height)/2, SCREEN_WIDTH*0.4677, SCREEN_WIDTH*0.985)];
    _extraImg.userInteractionEnabled = YES;
    _extraImg.image = [UIImage imageNamed:@"current_member_list"];
    [footer addSubview:_extraImg];
       

    UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, _rightView.y-(SCREEN_WIDTH*0.985-_rightView.height)/2, SCREEN_WIDTH*0.28, SCREEN_WIDTH*0.985)];
    leftView.backgroundColor = LightBGColor;
    leftView.layer.masksToBounds = YES;
    [footer addSubview:leftView];
    
    UIImageView *leftImg = [[UIImageView alloc] initWithFrame:CGRectMake(0, (leftView.height-_rightView.height)/2, SCREEN_WIDTH, _rightView.height)];
    leftImg.image = [UIImage imageNamed:@"member_info_1"];
    [leftView addSubview:leftImg];
    
    
    if (hasMembership) {
        if ([self.groupInfo[@"membership"][@"planType"] integerValue]==1) {
            [self applySelViewStateForIndex:0 animated:NO];
            [_cashArray.firstObject setValue:@"1" forKey:@"sel"];
            self.memberInfo.image = [UIImage imageNamed:@"member_info_1"];
        }else if ([self.groupInfo[@"membership"][@"planType"] integerValue]==2){
            [self applySelViewStateForIndex:1 animated:NO];
            [_cashArray[1] setValue:@"1" forKey:@"sel"];
            self.memberInfo.image = [UIImage imageNamed:@"member_info_2"];
        }else if ([self.groupInfo[@"membership"][@"planType"] integerValue]==3){
            [self applySelViewStateForIndex:2 animated:NO];
            [_cashArray.lastObject setValue:@"1" forKey:@"sel"];
            self.memberInfo.image = [UIImage imageNamed:@"member_info_3"];
        }
    }else{
        
        _current = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-28, _rightView.y+(_rightView.height-88)/2, 28, 88)];
        [_current setBackgroundImage:[UIImage imageNamed:@"current_member"] forState:UIControlStateNormal];
        [footer addSubview:_current];
        
        [[_current rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [UIView animateWithDuration:0.3 animations:^{
                self.rightView.x=SCREEN_WIDTH*0.28-self.selView.x;
                self.extraImg.x = SCREEN_WIDTH-self.extraImg.width;
            }];
            self.current.hidden = YES;
        }];
        
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        [[tap rac_gestureSignal] subscribeNext:^(id x) {
            [UIView animateWithDuration:0.3 animations:^{
                self.rightView.x=SCREEN_WIDTH*0.28;
                self.extraImg.x = SCREEN_WIDTH;
            }];
            self.current.hidden = NO;
        }];
        [self.extraImg addGestureRecognizer:tap];
        
        if ([_groupInfo[@"memberCount"] integerValue]<=2) {
            [self applySelViewStateForIndex:0 animated:NO];
            [_cashArray.firstObject setValue:@"1" forKey:@"sel"];
            self.memberInfo.image = [UIImage imageNamed:@"member_info_1"];
        }else {
            [self applySelViewStateForIndex:2 animated:NO];
            [_cashArray.lastObject setValue:@"1" forKey:@"sel"];
            self.memberInfo.image = [UIImage imageNamed:@"member_info_3"];
        }
    }

    UILabel *question = [[UILabel alloc] initWithFrame:CGRectMake(16, leftView.maxY+38, SCREEN_WIDTH-32, 32)];
    question.text = @"常见问题";
    question.font = MEDIUM_FONT(26);
    question.textColor = RealBlackColor;
    [footer addSubview:question];
    
    UIImageView *question1 = [[UIImageView alloc] initWithFrame:CGRectMake(16, question.maxY+16, SCREEN_WIDTH-32, (SCREEN_WIDTH-32)*0.303)];
    question1.image = [UIImage imageNamed:@"cash_question_1"];
    [footer addSubview:question1];
    
    UIImageView *question2 = [[UIImageView alloc] initWithFrame:CGRectMake(16, question1.maxY+16, SCREEN_WIDTH-32, (SCREEN_WIDTH-32)*0.368)];
    question2.image = [UIImage imageNamed:@"cash_question_2"];
    [footer addSubview:question2];
    
    UIImageView *question3 = [[UIImageView alloc] initWithFrame:CGRectMake(16, question2.maxY+16, SCREEN_WIDTH-32, (SCREEN_WIDTH-32)*0.434)];
    question3.image = [UIImage imageNamed:@"cash_question_3"];
    [footer addSubview:question3];
    
    UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-296)/2, question3.maxY+27, 296, 135)];
    img.image = [UIImage imageNamed:@"cash_img"];
    [footer addSubview:img];
    
    footer.height = footer.subviews.lastObject.maxY+129;
    [self updateScrollContentSize];

    
    UIView *bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-129, SCREEN_WIDTH, 129)];
    [self.view addSubview:bottomView];
    
    CALayer *infoLayer = [CALayer layer];
    infoLayer.frame = bottomView.bounds;
    infoLayer.masksToBounds = NO;
    infoLayer.backgroundColor = RealWhiteColor.CGColor;
    infoLayer.shadowColor = RealBlackColor.CGColor;
    infoLayer.shadowOffset = CGSizeMake(0,2);
    infoLayer.shadowOpacity = 0.3;
    infoLayer.shadowRadius = 3;
    [bottomView.layer addSublayer:infoLayer];
    
    UIButton *cashButton = [[UIButton alloc] initWithFrame:CGRectMake(16, 8, SCREEN_WIDTH-32, 60)];
    cashButton.layer.masksToBounds = YES;
    [cashButton.layer setCornerRadius:22];
    cashButton.backgroundColor = NormalMainColor;
    [cashButton setTitleColor:RealWhiteColor forState:UIControlStateNormal];
    if ([self.groupInfo[@"membership"] isKindOfClass:[NSDictionary class]]) {
        [cashButton setTitle:@"续费会员" forState:UIControlStateNormal];
    }else{
        [cashButton setTitle:@"开通会员" forState:UIControlStateNormal];
    }
    [cashButton.titleLabel setFont:MEDIUM_FONT(16)];
    [bottomView addSubview:cashButton];
    [[cashButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        UIImpactFeedbackGenerator *feedBackGenertor = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
        [feedBackGenertor impactOccurred];
        for (int i = 0; i < self.cashArray.count; i ++) {
            NSDictionary *dic = self.cashArray[i];
            if ([dic[@"sel"] integerValue]>0) { 
                NSMutableDictionary *param = [NSMutableDictionary dictionary];
                [param setValue:@(i+1) forKey:@"type"];
                CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                [manager encryptedPOST:@"/system/group/membership/plans"
                parameters:param
                success:^(NSDictionary *responseObject) {
                    if ([responseObject[@"code"] integerValue]==200 && [responseObject[@"data"] isKindOfClass:[NSArray class]]) {
                        if ([responseObject[@"data"] count]>0) {
                            if ([[responseObject[@"data"] firstObject][@"memberNum"] integerValue]>=[self.groupInfo[@"memberCount"] integerValue]) {
                                CashView *view = [[CashView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) CashInfo:responseObject[@"data"] GroupInfo:self.groupInfo];
                                [self.view addSubview:view];
                                view.CashViewBlock = ^(NSInteger index) {
                                    PolicyWebViewController *vc = [[PolicyWebViewController alloc] initWithRelativePath:(index==0?@"http://m.tanhuos.com/user_agreement.html":@"http://m.tanhuos.com/privacy_policy.html")];
                                    vc.modalPresentationStyle = UIModalPresentationPageSheet;
                                    [self presentViewController:vc animated:YES completion:nil];
                                };
                            }else{
                                [[HCToast shareInstance] showToast:[NSString stringWithFormat:@"仅支持%@人家庭开通",[responseObject[@"data"] firstObject][@"memberNum"]]];
                            }
                        }
                    }
                }
                failure:^(NSError *aError) {
                    
                }];
                break;
            }
        }        
    }];
    
    
    UILabel *groupInfo = [[UILabel alloc] initWithFrame:CGRectMake(16, cashButton.maxY+10, SCREEN_WIDTH-32, 16)];
    groupInfo.textColor = GraryTooHeavyColor;
    groupInfo.textAlignment = NSTextAlignmentCenter;
    groupInfo.font = DEFAULT_FONT(12);
    groupInfo.text = [NSString stringWithFormat:@"为 “%@” %@",self.groupInfo[@"name"],([self.groupInfo[@"membership"] isKindOfClass:[NSDictionary class]]?@"续费":@"开通")];
    [bottomView addSubview:groupInfo];
    if (!hasMembership) {
        [self updateCardViewsAnimated:NO];
    }
}



#pragma mark - Private

- (void)setupCardsContainerBelowY:(CGFloat)startY
{
    self.cardsContainer = [[UIView alloc] initWithFrame:CGRectMake(0, startY, SCREEN_WIDTH, 0)];
    self.cardsContainer.backgroundColor = LightBGColor;
    [self.scrollView addSubview:self.cardsContainer];
    [self.cardViews removeAllObjects];
    CGFloat cardY = 0.f;
    for (NSInteger i = 0; i < self.cashArray.count; i++) {
        CashTableViewCell *cell = [[CashTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];
        cell.frame = CGRectMake(0, cardY, SCREEN_WIDTH, [self heightForCardAtIndex:i]);
        [cell loadWithInfo:self.cashArray[i]];
        cell.tag = 1000 + i;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(cardTapped:)];
        [cell addGestureRecognizer:tap];
        [self.cardsContainer addSubview:cell];
        [self.cardViews addObject:cell];
        cardY = CGRectGetMaxY(cell.frame);
    }
    self.cardsContainer.height = cardY;
}

- (CGFloat)heightForCardAtIndex:(NSInteger)index
{
    if (index < 0 || index >= self.cashArray.count) {
        return 0.f;
    }
    BOOL selected = [self.cashArray[index][@"sel"] integerValue]==1;
    CGFloat baseHeight = (SCREEN_WIDTH-32)*(selected?0.367:0.237);
    return baseHeight+12;
}

- (void)updateCardViewsAnimated:(BOOL)animated
{
    if (!self.cardsContainer || self.cardViews.count == 0) {
        [self updateScrollContentSize];
        return;
    }
    CGFloat cardY = 0.f;
    for (NSInteger i = 0; i < self.cardViews.count; i++) {
        CashTableViewCell *cell = self.cardViews[i];
        [cell loadWithInfo:self.cashArray[i]];
        CGFloat targetHeight = [self heightForCardAtIndex:i];
        CGRect targetFrame = CGRectMake(0, cardY, SCREEN_WIDTH, targetHeight);
        if (animated) {
            [UIView animateWithDuration:0.25 animations:^{
                cell.frame = targetFrame;
                [cell layoutIfNeeded];
            }];
        }else{
            cell.frame = targetFrame;
        }
        cardY = CGRectGetMaxY(targetFrame);
    }
    self.cardsContainer.height = cardY;
    if (self.footerView) {
        CGFloat footerY = self.cardsContainer.y + self.cardsContainer.height;
        if (animated) {
            [UIView animateWithDuration:0.25 animations:^{
                self.footerView.y = footerY;
            }];
        }else{
            self.footerView.y = footerY;
        }
    }
    [self updateScrollContentSize];
}

- (void)cardTapped:(UITapGestureRecognizer *)tap
{
    NSInteger index = tap.view.tag - 1000;
    [self handleCardSelectionAtIndex:index];
}

- (void)handleCardSelectionAtIndex:(NSInteger)index
{
    if (index < 0 || index >= self.cashArray.count) {
        return;
    }
    if (self.cardViews.count == 0) {
        return;
    }
    if ([self.cashArray[index][@"sel"] integerValue]==1) {
        return;
    }
    for (int i = 0; i < self.cashArray.count; i ++) {
        NSMutableDictionary *dic = self.cashArray[i];
        if ([dic[@"sel"] integerValue]==1) {
            [dic setValue:@"0" forKey:@"sel"];
        }
    }
    UIImpactFeedbackGenerator *feedBackGenertor = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
    [feedBackGenertor impactOccurred];
    [self.cashArray[index] setValue:@"1" forKey:@"sel"];
    [self applySelViewStateForIndex:index animated:YES];
    self.memberInfo.image = [UIImage imageNamed:[NSString stringWithFormat:@"member_info_%ld",(long)(index+1)]];
    [self updateCardViewsAnimated:YES];
    
    [UIView animateWithDuration:0.3 animations:^{
        self.rightView.x=SCREEN_WIDTH*0.28;
        self.extraImg.x = SCREEN_WIDTH;
    }];
    self.current.hidden = NO;
}

- (void)applySelViewStateForIndex:(NSInteger)index animated:(BOOL)animated
{
    void (^changes)(void) = ^{
        if (index==0) {
            self.selView.x = 0;
            self.selView.backgroundColor = [UIColor colorWithRed:255/255.0 green:138/255.0 blue:182/255.0 alpha:0.2/1];
        }else if (index==1){
            self.selView.x = SCREEN_WIDTH*0.224;
            self.selView.backgroundColor = [UIColor colorWithRed:113/255.0 green:124/255.0 blue:244/255.0 alpha:0.2/1];
        }else if (index==2){
            self.selView.x = SCREEN_WIDTH*0.448;
            self.selView.backgroundColor = [UIColor colorWithRed:230/255.0 green:186/255.0 blue:135/255.0 alpha:0.2/1];
        }
    };
    if (animated) {
        [UIView animateWithDuration:0.3 animations:changes];
    }else{
        changes();
    }
}

- (void)updateScrollContentSize
{
    if (!self.scrollView) {
        return;
    }
    CGFloat maxHeight = 0.f;
    for (UIView *subview in self.scrollView.subviews) {
        CGFloat bottom = subview.y + subview.height;
        if (bottom > maxHeight) {
            maxHeight = bottom;
        }
    }
    CGFloat minHeight = self.scrollView.height+1;
    self.scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, MAX(maxHeight, minHeight));
}

@end
